<template>
  <el-card>
    <el-form label-width="120px" :model="adminInfo" :rules="addRules" ref="addForm">
      <el-form-item label="角色名称" prop="roleid">
        <el-select v-model="adminInfo.roleid">
          <el-option label="请选择" value></el-option>
          <el-option
            :label="item.rolename"
            v-for="item in roleList"
            :key="item.id"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="管理员账号" prop="username">
        <el-input v-model="adminInfo.username" placeholder="请输入登录账号"></el-input>
      </el-form-item>
      <el-form-item label="管理员密码" prop="password">
        <el-input
          type="password"
          :show-password="true"
          v-model="adminInfo.password"
          placeholder="请输入登录密码"
        ></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="adminInfo.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="2">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit('addForm')">立即添加</el-button>
        <el-button type="default" @click="reset('addForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  data() {
    // 自定义表单校验规则
    const roleRequired = (rule, value, callback) => {
      console.log(value);
      if (value == "") {
        return callback(new Error("请选择角色"));
      }
      callback();
    };
    return {
      adminInfo: {
        username: "",
        password: "",
        roleid: "",
        status: 1
      },
      roleList: [],
      addRules: {
        roleid: {
          validator: roleRequired,
          message: "请输选择角色",
          trigger: "blur"
        },
        username: { required: true, message: "请输入用户名", trigger: "blur" },
        password: { required: true, message: "请输入密码", trigger: "blur" }
      }
    };
  },
  created() {
    this.getRoleList();
  },
  methods: {
    // 获取角色列表
    async getRoleList() {
      const res = await this.$http.get("/api/rolelist");
      if (res.code == 200) {
        this.roleList = res.list;
      }
    },
    submit(form) {
      this.$refs[form].validate(async valid => {
        if (valid) {
          const res = await this.$http.post("/api/useradd", this.adminInfo);
          console.log(res);
          if (res.code == 200) {
            this.$refs[form].resetFields();
            return this.$success("操作成功");
          }
          this.$error("操作失败");
        } else {
          return false;
        }
      });
    },
    reset(form) {
      this.$refs[form].resetFields();
    }
  }
};
</script>

<style>
</style>